/**
 * 聊天室的主要功能
 * 1.连接socket.io服务
 * */
const socket = io('http://127.0.0.1:3000')

var username, avatar
/**
 * 2.登录功能
 * */
$('#login_avatar li').on('click', function () {
  $(this).addClass('now').siblings().removeClass('now')
})
// 3.点击按钮，登录
$('#loginBtn').on('click', function () {
  let username = $('#username').val().trim()
  if (!username) {
    alert('请输入用户名')
    return
  }
  let avatar = $('#login_avatar li.now img').attr('src')
  // 需要告诉socket.io服务登录
  socket.emit('login', {
    username: username,
    avatar: avatar
  })
})

// 监听登录失败的请求
socket.on('loginError', data => {
  alert('登录失败')
})
// 监听登录成功的请求
socket.on('loginSuccess', data => {
  $('.login_box').fadeOut()
  $('.container').fadeIn()
  $('.avatar_url').attr('src', data.avatar)
  $('.username').html(data.username)
  username = data.username
  avatar = data.avatar
})

// 监听添加用户的消息
socket.on('addUser', data => {
  // 添加一条系统消息
  $('.box-bd').append(`
    <div class="system">
      <p class="message_system">
        <span class="content">${data.username}加入了群聊</span>
      </p>
    </div>
  `)
  scrollIntoView()
})
// 左侧用户列表
socket.on('userList', data => {
  console.log(data)
  $('.groupNum').text(data.length)
  $('.user-list ul').empty()
  data.forEach(item => {
    $('.user-list ul').append(`
      <li class="user">
        <div class="avatar"><img src="${item.avatar}"></div>
        <div class="name">${item.username}</div>
      </li>
    `)
  })
})

// 监听用户离开的消息
socket.on('delUser', data => {
  $('.box-bd').append(`
    <div class="system">
      <p class="message_system">
        <span class="content">${data.username}离开了群聊</span>
      </p>
    </div>
  `)
  scrollIntoView()
})

// 聊天功能
$('#btn-send').on('click', () => {
  let content = $('#content').html()
  $('#content').empty('')
  if (!content) return alert('不能发送空白消息')
  socket.emit('sendMsg', {
    msg: content,
    username: username,
    avatar: avatar
  })
})

// 监听聊天消息
socket.on('receiveMsg', data => {
  // 把接收到的消息显示到聊天窗口中
  if (data.username === username) {
    $('.box-bd').append(`
      <div class="message-box">
        <div class="my message">
          <img class="avatar" src="${data.avatar}" alt="" />
          <div class="content">
            <div class="bubble">
              <div class="bubble_cont">${data.msg}</div>
            </div>
          </div>
        </div>
      </div>
    `)
  } else {
    $('.box-bd').append(`
      <div class="message-box">
        <div class="other message">
          <img class="avatar" src="${data.avatar}" alt="" />
          <div class="content">
            <div class="nickname">${data.username}</div>
            <div class="bubble">
              <div class="bubble_cont">${data.msg}</div>
            </div>
          </div>
        </div>
      </div>  
    `)
  }
  scrollIntoView()
})

function scrollIntoView() {
  $('.box-bd').children(':last').get(0).scrollIntoView()
}

// 发送图片功能
$('#file').on('change', function () {
  var file = this.files[0]

  // 需要把这个文件发送到服务器，借助于新增的fileReader
  var fr = new FileReader()
  fr.readAsDataURL(file)
  fr.onload = function () {
    console.log(fr.result)
    socket.emit('sendImg', {
      username: username,
      avatar: avatar,
      img: fr.result
    })
  }
})

socket.on('receiveImg', data => {
  // 把接收到的消息显示到聊天窗口中
  if (data.username === username) {
    $('.box-bd').append(`
      <div class="message-box">
        <div class="my message">
          <img class="avatar" src="${data.avatar}" alt="" />
          <div class="content">
            <div class="bubble">
              <div class="bubble_cont"><img src="${data.img}" /></div>
            </div>
          </div>
        </div>
      </div>
    `)
  } else {
    $('.box-bd').append(`
      <div class="message-box">
        <div class="other message">
          <img class="avatar" src="${data.avatar}" alt="" />
          <div class="content">
            <div class="nickname">${data.username}</div>
            <div class="bubble">
              <div class="bubble_cont"><img src="${data.img}" /></div>
            </div>
          </div>
        </div>
      </div>  
    `)
  }

  // 等待图片加载完成，在滚动到底部
  $('.box-bd img:last').on('load', function () {
    scrollIntoView()
  })
})

// 初始化jquery-emoji插件
$('.face').on('click', function () {
  $('#content').emoji({
    button: '.face',
    showTab: false,
    position: 'topRight',
    icons: [{
      name: "QQ表情",
      path: "../lib/img/qq/",
      maxNum: 91,
      excludeNums: [41, 45, 54],
      file: ".gif"
    }]
  })
})

